package com.cz.video.website.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cz.video.common.constant.CommonConstants;
import com.cz.video.common.core.domain.PageQuery;
import com.cz.video.common.core.page.TableDataInfo;
import com.cz.video.common.exception.ServiceException;
import com.cz.video.common.helper.LoginHelper;
import com.cz.video.common.utils.StringUtils;
import com.cz.video.common.utils.TreeBuildUtils;
import com.cz.video.website.domain.WebsiteComment;
import com.cz.video.website.domain.bo.WebsiteCommentBo;
import com.cz.video.website.domain.vo.WebsiteCommentVo;
import com.cz.video.website.mapper.WebsiteCommentMapper;
import com.cz.video.website.service.IWebsiteCommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author LLF
 * @since 2023-10-16
 */
@Service
@RequiredArgsConstructor
public class WebsiteCommentServiceImpl extends ServiceImpl<WebsiteCommentMapper, WebsiteComment> implements IWebsiteCommentService {
    private final WebsiteCommentMapper commentMapper;

    /**
     * 新增保存评论表信息
     *
     * @param websiteComment 用户信息
     * @return 结果
     */
    @Override
    public int insertComment(WebsiteCommentBo websiteComment) {
        // 新增评论表信息
        int rows = commentMapper.insert(websiteComment);
        return rows;
    }
    /**
     * 修改评论表信息
     * @param websiteComment
     * @return
     */
    @Override
    public int updateComment(WebsiteCommentBo websiteComment) {
        return commentMapper.updateById(websiteComment);
    }

    /**
     * 分页查找评论表信息
     *
     * @param websiteComment
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<WebsiteCommentVo> selectPageCommentList(WebsiteCommentBo websiteComment, PageQuery pageQuery) {
        Page<WebsiteCommentVo> page= commentMapper.selectPageCommentList(this.buildQueryWrapper(websiteComment),pageQuery.build(),LoginHelper.getUserId());
        return TableDataInfo.build(page);
    }


    @Override
    //返回用户细节（ID和头像）
    public TableDataInfo<WebsiteCommentVo> selectCommentsWithUserDetails(WebsiteCommentBo websiteComment, PageQuery pageQuery) {
        Page<WebsiteCommentVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        page.setRecords(commentMapper.selectPageCommentListWithUserDetails(page, websiteComment));

        TableDataInfo<WebsiteCommentVo> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.OK.value()); // 设置状态码为 200 OK，根据需要自行调整

        return tableDataInfo;
    }

    @Override
    public TableDataInfo<?> listParent(WebsiteCommentBo commentBo, PageQuery pageQuery) {
        if (commentBo.getTargetId()==null)
            throw new ServiceException("没有指定视频");
        /**
         * 关闭mybatis自己的查询总数
         */
        Page<WebsiteCommentVo> page = pageQuery.build();
        //设置按创建时间排序
        if (ObjectUtil.isNotNull(commentBo.getCommentId())&& StringUtils.isEmpty(pageQuery.getOrderByColumn()))
            pageQuery.setOrderByColumn("wc.create_time");
        page.setSearchCount(false);
        int total=commentMapper.countAll(commentBo.getTargetId());
        commentMapper.selectPageCommentList(this.buildQueryWrapper(commentBo), page, LoginHelper.getUserId());
        TableDataInfo<WebsiteCommentVo> pageTableDataInfo=TableDataInfo.<WebsiteCommentVo>build(page);
        pageTableDataInfo.setTotal(total);
        return pageTableDataInfo;
    }

    @Override
    public List<WebsiteCommentVo> getReplyList(List<Long> parentIds) {
        return commentMapper.selectMostLikeReplyList(parentIds,LoginHelper.getUserId());
    }

    @Override
    public List buildCommentTreeSelect(List<WebsiteCommentVo> commentList) {
        if (CollUtil.isEmpty(commentList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(commentList, (commentVo, tree) ->
            tree.setId(commentVo.getCommentId())
                .setParentId(commentVo.getParentId())
                .put("comment",commentVo)
        );
    }

    @Override
    public int deleteById(Long id) {
        return commentMapper.deleteById(id);
    }
    /**
     * 根据查询条件构建query wrapper
     *
     * @param websiteComment 查询条件
     *
     * @return query wrapper
     */
    private Wrapper<WebsiteComment> buildQueryWrapper(WebsiteCommentBo websiteComment) {
        Map<String, Object> params = websiteComment.getParams();
        QueryWrapper<WebsiteComment> wrapper = Wrappers.query();

        wrapper.eq("wc.del_flag", CommonConstants.NOT_DELETED)
            .eq(ObjectUtil.isNotNull(websiteComment.getTargetId()), "wc.target_id", websiteComment.getTargetId())
            .eq(ObjectUtil.isNotNull(websiteComment.getUserId()), "wc.user_id", websiteComment.getUserId())
            .eq(ObjectUtil.isNotNull(websiteComment.getParentId()), "wc.parent_id", websiteComment.getParentId())
            .eq(ObjectUtil.isNotNull(websiteComment.getStatus()), "wc.status", websiteComment.getStatus())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                "wc.create_time", params.get("beginTime"), params.get("endTime"));
        return wrapper;
    }

}
